<?php

namespace app\agent\model;

use app\common\model\Upload;
use app\model\Agent as AgentModel;
use think\facade\Db;

class Agent
{
    protected $error = '';
    protected $table = 'agent';

    protected const PASS_LOGIN = 1;
    protected const SMS_LOGIN = 2;

    /**
     * 登录.
     */
    public function login($data)
    {
        // if (empty($data['type'])) {
        //     $this->setError('登录类型有误[type]');
        //     return false;
        // }

        // switch ($data['type']) {
        //     case self::PASS_LOGIN:
        //         $agent = $this->pass_login($data);
        //         break;
        //     case self::SMS_LOGIN:
        //         $agent = $this->sms_login($data);
        //         break;
        //     default:
        //         $this->setError('登录类型有误[type]');
        //         return false;
        //         break;
        // }
        $agent = $this->pass_login($data);
        if (false === $agent) {
            return false;
        }
        $this->loginRecord($agent);

        return $agent['id'];
    }

    /**
     * 登录日志.
     */
    public function loginRecord($agent)
    {
        Db::name('agent_login_log')->insert([
            'agent_id' => $agent['id'],
            'username' => $agent['username'],
            'ip' => request()->ip(),
            'login_at' => date('Y-m-d H:i:s'),
            'useragent' => request()->header('user-agent'),
        ]);
    }

    /**
     * 账号密码登录.
     */
    public function pass_login($data)
    {
        if (empty($data['username'])) {
            $this->setError('请输入手机号码');

            return false;
        }
        if (empty($data['password'])) {
            $this->setError('请输入密码');

            return false;
        }

        $lockKey = $data['username'].'_agent_login_lock_key';
        $val = cache($lockKey);
        if ($val > 3) {
            $this->setError('连续多次密码输入错误，账号已被锁定');

            return false;
        }

        $agent = Db::name($this->table)
            ->where('username', $data['username'])
            ->find();
        if (empty($agent) || !password_verify($data['password'], $agent['password'])) {
            $this->setError('账号或者密码有误');
            $this->loginRecord([
                'id' => 1,
                'username' => '验证错误:'.$data['username'].$data['password']
            ]);
            $val = intval($val) + 1;
            cache($lockKey, $val, 3600*24);

            return false;
        }

        if ($agent['is_deleted']) {
            $this->setError('登录失败，您的账号已被删除，请联系客服人员');

            return false;
        }
        if (1 != $agent['status']) {
            $this->setError('登录失败，您的账号已经被禁用');

            return false;
        }

        cache($lockKey, null);

        return $agent;
    }

    /**
     * 短信验证码登录.
     */
    public function sms_login($data)
    {
        $this->setError('没有这回事');

        return false;
        if (empty($data['mobile'])) {
            $this->setError('请输入手机号码');

            return false;
        }
        if (!checkMobile($data['mobile'])) {
            $this->setError('请输入正确的手机号码');

            return false;
        }
        if (empty($data['password'])) {
            $this->setError('请输入短信验证码');

            return false;
        }

        $data['code'] = $data['password'];
        if (false === Sms::checkVerifyCode($data)) {
            $this->setError('短信验证码有误');

            return false;
        }
        Sms::deleteVerifyCode($data);

        $agent = Db::name($this->table)
            ->where('account', $data['mobile'])
            ->where('delete_time', 0)
            ->find();
        if (empty($agent)) {
            // 账号不存在，自动注册一个
            $agent = $this->insertAgent($data);
            if (empty($agent)) {
                $this->setError('登录失败，请稍后重试');

                return false;
            }
        }
        if (1 != $agent['status']) {
            $this->setError('登录失败，您的账号已经被禁用');

            return false;
        }

        return $agent;
    }

    /**
     * 设置错误信息.
     */
    public function setError($error)
    {
        $this->error = $error;
    }

    /**
     * 获取错误信息.
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 修改密码
     */
    public function updatePassword($params)
    {
        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $params['agent_id'])
                ->update([
                    'password' => password_hash($params['password'], PASSWORD_DEFAULT),
                ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('修改失败：'.$e->getMessage());
        }

        return success('修改成功');
    }

    /**
     * 上传头像.
     */
    public function uploadAvatar($agentId)
    {
//        $image = request()->file('image');
//        try {
//            // 上传到本地服务器
//            $savename = \think\facade\Filesystem::disk('public')->putFile('avatar', $image);
//            $savename = str_replace('\\', '/', $savename);
//            $avatar = request()->domain().'/storage/'.$savename;
//            Db::name('agent')
//                ->where('id', $agentId)
//                ->update([
//                    'avatar' => $avatar,
//                ]);
//
//            return success('上传成功', [
//                'url' => $avatar,
//            ]);
//        } catch (\Exception $e) {
//            return fail($e->getMessage());
//        }
        try {
            $avatar = '';
            $params = [
                'dirName' => 'avatar',
            ];
            $result = (new Upload())->image($params);

            $result = json_decode($result->getContent(),true);
            if ($result['data']) {
                $avatar = $result['data']['url'];
            }
            if (empty($avatar)) {
                return fail('上传失败');
            }
            /**
             * @var AgentModel $agent
             */
            $agent = AgentModel::query()->where('id', $agentId)->find();
            $agent->avatar = $avatar;
            $agent->save();
            return success('上传成功', [
                'url' => $avatar,
            ]);
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }
    }

    /**
     * 资金明细.
     */
    public function getBalanceList($params)
    {
        $where = [];
        $where[] = ['agent_id', '=', $params['agent']['id']];
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        if (SETTLE_TYPE_PROFIT == $params['agent']['settle_type']) {
            $typeIds = [
                BALANCE_MOBILE_RECHARGE,
                BALANCE_WITHDRAW_APPLY,
                BALANCE_WITHDRAW_CANCEL,
                BALANCE_WITHDRAW_REJECT,
                BALANCE_MOBILE_PROFIT,
                BALANCE_ONLINE_RECHARGE,
                BALANCE_MOBILE_REFUND,
                BALANCE_OIL_COMMISS,
            ];
        } else {
            $typeIds = [
                BALANCE_MOBILE_RECHARGE,
                BALANCE_AGENT_RECHARGE,
                BALANCE_MOBILE_REFUND,
                BALANCE_ONLINE_RECHARGE,
                BALANCE_OIL_COMMISS,
            ];
        }
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        } else {
            $where[] = ['type', 'in', $typeIds];
        }
        $typeList = config('app.balanceTypeList');
        $list = Db::name('agent_balance_log')
            ->where($where)
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['type_name'] = $typeList[$v['type']];
        }
        foreach ($typeList as $k => $v) {
            if (!in_array($k, $typeIds)) {
                unset($typeList[$k]);
            }
        }
        $list['balanceTypeList'] = $typeList;

        return success('操作成功', $list);
    }
}
